package com.feeyin.radar.crm.dao.impl;

import com.feeyin.radar.commons.StringUtils;
import com.feeyin.radar.crm.dao.CustomerShareDAO;
import com.feeyin.radar.crm.model.CustomerShare;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

public class CustomerShareDAOImpl extends SqlMapClientDaoSupport
  implements CustomerShareDAO
{
  public List getActivityCustomerSharesByCustomerId(Integer customerId)
  {
    return getSqlMapClientTemplate().queryForList("getActivityCustomerSharesByCustomerId", customerId);
  }

  public CustomerShare getCustomerShareByCustomerIdAndSalePersonId(Integer customerId, Integer salePersonId)
  {
    Map map = new HashMap();
    map.put("customerId", customerId);
    map.put("salePersonId", salePersonId);
    return (CustomerShare)getSqlMapClientTemplate().queryForObject("getCustomerShareByCustomerIdAndSalePersonId", map);
  }

  public boolean insertCustomerShare(CustomerShare customerShare) {
    Integer result = (Integer)getSqlMapClientTemplate().insert("insertCustomerShare", customerShare);
    return result != null;
  }

  public boolean insertCustomerShare(Integer customerId, Integer salePersonId, String isReadWrite)
  {
    if (customerId == null) return false;
    if (salePersonId == null) return false;
    if (StringUtils.isEmpty(isReadWrite)) isReadWrite = "0";

    if (getCustomerShareByCustomerIdAndSalePersonId(customerId, salePersonId) != null) {
      CustomerShare cShare = new CustomerShare();
      cShare = new CustomerShare();
      cShare.setCustomerId(customerId);
      cShare.setSalePersonId(salePersonId);
      cShare.setIsCurShare("1");
      cShare.setIsReadWrite(isReadWrite);
      updateCustomerShare(cShare);
    } else {
      CustomerShare customerShare = new CustomerShare();
      customerShare.setCustomerId(customerId);
      customerShare.setSalePersonId(salePersonId);
      customerShare.setIsCurShare("1");
      customerShare.setIsReadWrite(isReadWrite);
      insertCustomerShare(customerShare);
    }
    return true;
  }

  public boolean updateCustomerShare(CustomerShare customerShare) {
    Integer result = Integer.valueOf(getSqlMapClientTemplate().update("updateCustomerShare", customerShare));
    return result != null;
  }

  public boolean deleteCustomerShare(Integer customerId)
  {
    if (customerId == null) return false;
    CustomerShare customerShare = new CustomerShare();
    customerShare.setCustomerId(customerId);
    customerShare.setIsCurShare("0");
    return updateCustomerShare(customerShare);
  }
}